package com.wmyg.antifake.gs1.ns2.converters;

import com.wmyg.antifake.gs1.ns2.ExceptionMessage;
import com.wmyg.antifake.gs1.ns2.TSDQueryByGTINResponse;
import org.dom4j.Element;

import java.util.List;

/**
 * @program: antifake
 * @description: 响应转换器
 * @author: wong
 * @create: 19-4-23
 */
public class ResponseConverter {

    public static TSDQueryByGTINResponse converter(Element responseElement) {
        TSDQueryByGTINResponse response = new TSDQueryByGTINResponse();
        List<Element> children = responseElement.elements();
        for (Element element :
                children) {
            switch (element.getName()) {
                case "productData":
                    response.setProductData(ProductDataConverter.converter(element));
                    break;
                default:
                    checkException(element, response);
            }
        }
        return response;
    }

    private static void checkException(Element element, TSDQueryByGTINResponse response) {
        System.out.println(element.getName());
        if (element.getName().endsWith("Exception")) {
            ExceptionMessage exceptionMessage = new ExceptionMessage();
            exceptionMessage.setExceptionName(element.getName());
            if (element.elements().size() > 0) {
                exceptionMessage.setExceptionReason(((Element)(element.elements().get(0))).getText());
            }
            response.setExceptionMessage(exceptionMessage);
        } else {
            response.setMap(MapConverter.elementToMap(element));
        }
    }

}
